<?php
namespace app\api\controller;

use think\Controller;
use think\Db;
use think\Session;
use think\Request;
use think\Loader;
use ElemeOpenApi\Config\Config;
use ElemeOpenApi\OAuth\OAuthClient;
use ElemeOpenApi\Api\UserService;
use ElemeOpenApi\Api\OrderService;
use ElemeOpenApi\Api\ShopService;

/**
* 饿了么企业应用接口类 created by hfc 6.20
*/
class Authorization extends Controller
{
	//此处需要填写对应的参数
	private $app_key = '4Oh6PuxhkX';
	private $app_secret = 'f079ac2b70adfc257b011b16be3251285ed111da';
	private $callback_url = 'http://hdpt.yao2099.com/api/Authorization/callBack';
	private $sandbox = true;//true

	//正式环境
	// private $app_key = 'Br2jZSg9UW';
	// private $app_secret = '8af6ee1df35ad58e0c72f4ad8c0f9c19e412967f';
	// private $callback_url = 'https://pt.gzsanzhixiaoji.com/api/Authorization/callBack';
	// public $sandbox = false;//false
	
	private $scope = 'all';
	private $state = 'test';
	private $returnData;
	private $hasToken = false;
	private $config = null;
	private $client = null;
	private $userId = 0;


	public function _initialize()
	{
	    $this->config = new Config($this->app_key, $this->app_secret, $this->sandbox);
	    $this->client = new OAuthClient($this->config);
	    file_put_contents('elem.txt',"\r\n". 1236 .date("Y-m-d H:i:s").PHP_EOL,FILE_APPEND);
	    // file_put_contents('elem.txt',"\r\n". 1236 .config("session.expire").PHP_EOL,FILE_APPEND);

	    //维护token,过期之后使用refresh_token刷新token
	    $userId = Request::instance()->param('userId');
    	// $tokenData = session($userId);
    	$tokenData = Db::name('elemshop')->where(['userId'=>$userId])->find();
    	$hasToken = !empty($tokenData)?true:false;
    	// 是否有令牌
    	if($hasToken){
    		// $elemData = session($userId);
    		// $elemTokenData = session($elemData['userId']);
			// $elemTokenArr = json_decode(json_encode($elemTokenData),true);
			// $elemToken = $elemTokenArr['access_token']; 
			// $expires_in = $elemTokenArr['expires_in'];//过期时间
			// $refresh_token = $elemTokenArr['refresh_token'];//用来刷新token
			// $expires_time = $elemData['expires_time'];
			$elemData = json_decode($tokenData['content'],true);
    		$elemTokenData = Db::name('elemtoken')->where(['shop_id'=>$tokenData['id']])->find();
    		$elemTokenArr = json_decode($elemTokenData['content'],true);
    		$elemToken = $elemTokenArr['access_token']; 
			$expires_in = $elemTokenArr['expires_in'];//过期时间
			$refresh_token = $elemTokenArr['refresh_token'];//用来刷新token
			$expires_time = $elemData['expires_time'];
    		$nowTime = time();
    		 // file_put_contents('elem.txt',"\r\n". $elemData['expires_time'] .date("Y-m-d H:i:s").PHP_EOL,FILE_APPEND);

    		// 过期了刷新令牌
    		if($nowTime >= $expires_time){
    			$token = $this->client->get_token_by_refresh_token($refresh_token,$this->scope);
	    		$returnArr = json_decode(json_encode($token),TRUE);//对象转数组
    			if(!empty($returnArr['access_token'])){
		    		$user_service = new UserService($token, $this->config);
		    		$user = $user_service->get_user();
		    		$userArr = json_decode(json_encode($user),true);
		    		// $userArr['expires_time'] = strtotime('+30 day');//正式环境
		    		$userArr['expires_time'] = strtotime('+1 day');//沙箱环境 过期时间
		    		// session($userId,$userArr);
		    		// session($userArr['userId'],$token);

		    		// 饿了么商店信息
					$shop = [
					'userId' => $userId,
					'content' => json_encode($userArr),
					'time' => date('Y-m-d H:i:s')
					];
					Db::name('elemshop')->where(['userId'=>$userId])->update($shop);
					$elemShop = Db::name('elemshop')->where(['userId'=>$userId])->order('time desc')->find();
					$shop_id = $elemShop['shop_id'];
					//商店token
					$shopToken = [
					'content' => json_encode($returnArr),
					'elemShopId'=> $userArr['userId'],
					'shop_id'=>$shop_id,
					'time' => date('Y-m-d H:i:s')
					];
					Db::name('elemtoken')->where(['shop_id'=>$shop_id])->update($shopToken);
		    		// dump($_SESSION);
		    		// dump($elemTokenData);
    			}
    		}
    	}
    	// session(null);
	}

	public function auth_url(){
	    // 根据OAuth2.0中的对应state，scope和callback_url，获取授权URL
    	$userId = Request::instance()->param('userId');
    	// $tokenData = session($userId);
    	$tokenData = Db::name('elemshop')->where(['userId'=>$userId])->find();
    	$hasToken = !empty($tokenData)?1:0;
    	// file_put_contents('elem.txt',"\r\n".  .PHP_EOL,FILE_APPEND);
    	// file_put_contents('elem.txt',"\r\n". $hasToken .PHP_EOL,FILE_APPEND);
    	// file_put_contents('elem.txt',"\r\n". $userId .PHP_EOL,FILE_APPEND);
    	// file_put_contents('elem.txt',"\r\n". $tokenData .PHP_EOL,FILE_APPEND);
    	// file_put_contents('elem.txt',"\r\n". session($userId) .PHP_EOL,FILE_APPEND);
   //  	//是否有令牌
    	if($hasToken){
    		
    		echo "<script>alert('已授权');window.close();</script>";
    	}else{
    		$this->state = $userId;
	    	$auth_url = $this->client->get_auth_url($this->state, $this->scope, $this->callback_url);
	    	header('Location: '.$auth_url);
    	}
	}

// array(1) {
//   ["think"] => array(2) {
//     [374] => array(4) {
//       ["userId"] => int(393585216979213492)
//       ["userName"] => string(16) "sandbox_25981554"
//       ["authorizedShops"] => array(1) {
//         [0] => array(2) {
//           ["id"] => int(163785662)
//           ["name"] => string(24) "三只小鸡测试店铺"
//         }
//       }
//       ["expires_time"] => int(1529984596)
//     }
//     [393585216979213492] => object(stdClass)#3 (4) {
//       ["access_token"] => string(32) "40cad9d1f44de1fb3fccf13e33535307"
//       ["token_type"] => string(6) "Bearer"
//       ["expires_in"] => int(86400)
//       ["refresh_token"] => string(32) "267012684c84aa062eff07e3e45237db"
//     }
//   }
// }

	//回调地址
	public function callBack(){
		$code = Request::instance()->get('code');
		//通过授权得到的code，以及正确的callback_url，获取token
	    $token = $this->client->get_token_by_code($code, $this->callback_url);
	    $returnArr = json_decode(json_encode($token),TRUE);//对象转数组
	    if(!empty($returnArr['access_token'])){
	    	$user_service = new UserService($token, $this->config);
    		$user = $user_service->get_user();
    		$userArr = json_decode(json_encode($user),true);
    		// $userArr['expires_time'] = strtotime('+30 day');//正式环境
    		$userArr['expires_time'] = strtotime('+1 day');//沙箱环境 过期时间
    		$state = Request::instance()->get('state');
    		// session($state,$userArr);
    		// session($userArr['userId'],$token);

			// 饿了么商店信息
			$tokenData = Db::name('elemshop')->where(['userId'=>$state])->find();
			$shop = [
			'userId' => $state,
			'content' => json_encode($userArr),
			'time'=>date('Y-m-d H:i:s')
			];
			Db::name('elemshop')->insert($shop);
			$shop_id = Db::name('elemshop')->getLastInsID();
			//商店token
			$shopToken = [
			'content' => json_encode($returnArr),
			'elemShopId'=> $userArr['userId'],
			'shop_id'=>$shop_id,
			'time'=>date('Y-m-d H:i:s')
			];
			Db::name('elemtoken')->insert($shopToken);

	    	echo "<script>alert('授权成功');window.close();</script>";
	    	// echo "<script>alert('授权成功');window.close();</script>";
	    }else{
	    	echo "<script>alert('授权失败')</script>";
	    }
	}

	//获取商户账号信息
	public function getUserInfo(){
		$userId = Request::instance()->param('userId');
		$tokenData = Db::name('elemshop')->where(['userId'=>$userId])->find();
		$elemData = json_decode($tokenData['content'],true);
		// $elemData = session($userId);
		if(!empty($elemData)){
			$elemShopId = $elemData['authorizedShops'][0]['id'];
			// $elemTokenData = session($elemData['userId']);
			$elemTokenData = Db::name('elemtoken')->where(['shop_id'=>$tokenData['id']])->find();
    		$elemTokenArr = json_decode($elemTokenData['content'],true);
			// $elemTokenArr = json_decode(json_encode($elemTokenData),true);
			$elemToken = $elemTokenArr['access_token']; 
			return json(['status'=>1,'elemShopId'=>$elemShopId,'elemToken'=>$elemToken]);
		}else{
			return json(['status'=>0,'elemShopId'=>'','elemToken'=>'']);
		}

	}

	//获取店铺具体信息
	public function getShopInfo(){
		$userId = Request::instance()->param('userId');
		// $shopId = (int)Request::instance()->param('shopId');
		// $elemData = session($userId);
		$tokenData = Db::name('elemshop')->where(['userId'=>$userId])->find();
		$elemData = json_decode($tokenData['content'],true);
		if(!empty($elemData)){
			$elemShopId = $elemData['authorizedShops'][0]['id'];
			$elemTokenData = Db::name('elemtoken')->where(['shop_id'=>$tokenData['id']])->find();
    		$elemTokenArr = json_decode($elemTokenData['content'],true);
    		$token = json_decode($elemTokenData['content']);
			// $elemTokenData = session($elemData['userId']);
			$shop_service = new ShopService($token, $this->config);
		    $shop = $shop_service->get_shop($elemShopId);
			return json(['status'=>1,'shopInfo'=>$shop]);
		}else{
			return json(['status'=>0,'shopInfo'=>[]]);
		}
	}

	//获取所有订单
	public function getAllElemOrders(){
		$userId = Request::instance()->post('userId');
		$pageSize = Request::instance()->post('pageSize');
		$pageNo = Request::instance()->post('pageNo');

		// $elemData = session($userId);
		// $elemTokenData = session($elemData['userId']);
		// $elemTokenArr = json_decode(json_encode($elemTokenData),true);

		$tokenData = Db::name('elemshop')->where(['userId'=>$userId])->find();
		$elemData = json_decode($tokenData['content'],true);
		$elemShopId = $elemData['authorizedShops'][0]['id'];
		$elemTokenData = Db::name('elemtoken')->where(['shop_id'=>$tokenData['id']])->find();
		$elemTokenArr = json_decode($elemTokenData['content'],true);
		$token = json_decode($elemTokenData['content']);

		$elemToken = $elemTokenArr['access_token']; 
		$shop_id = $elemData['authorizedShops'][0]['id'];
		$page_no = $pageNo;
		$page_size = $pageSize;
		$date = date("Y-m-d",time());
		// $date = "2018-06-28";
		// $date = date("Y-m-d");
		// dump($_SESSION);
		
		file_put_contents('elem.txt',"\r\n123".json_encode($elemTokenArr),FILE_APPEND);
		$order_service = new OrderService($token, $this->config);
		$result = $order_service->get_all_orders($shop_id, $page_no, $page_size, $date);
		$date = date("Y-m-d",time());
		$time1 = $date.' 00:00:00';
		$time2 = $date.' 23:59:59';
		$date1 = strtotime($time1);
		$date2 = strtotime($time2);
		$elemIdArr = [];
		$hasDelivery = Db::name('send_order')->where(['type'=>4,'uid'=>$userId,'pay_status'=>array('gt',0),'time'=>array('between',[$date1,$date2])])->select();
		if(!empty($hasDelivery)){
			foreach($hasDelivery as $key =>$val){
				array_push($elemIdArr,$val['elemId']);
			}
		}
		ajaxReturn(['status'=>1,'data'=>$result,'elemIdArr'=>$elemIdArr]);
	}

	public function getPublish(){
		$userId = 374;
		// $userId = Request::instance()->post('userId');
		$date = date("Y-m-d",time());
		$time1 = $date.' 00:00:00';
		$time2 = $date.' 23:59:59';
		$date1 = strtotime($time1);
		$date2 = strtotime($time2);
		$hasDelivery = Db::name('send_order')->where(['type'=>4,'uid'=>$userId,'time'=>array('between',[$date1,$date2])])->select();
		// ajaxReturn(['status'=>1,'data'=>$hasDelivery]);
		// $date1 = '2018-06-28 0:0:0';
		// $date2 = '2018-06-28 23:59:59';
		// $hasDelivery = db('send_order')->where(['type'=>4])->whereTime('time', 'between', [$date1, $date2])->select();
		dump($hasDelivery);
		// echo $userId;
	}

	public function elemLoginOut(){
		$userId = Request::instance()->post('userId');
		$shop = Db::name('elemshop')->where(['userId'=>$userId])->find();
		if(!empty($shop)){
			Db::name('elemshop')->where(['userId'=>$userId])->delete();
			Db::name('elemtoken')->where(['shop_id'=>$shop['id']])->delete();
		}
		// $elemData = session($userId);
		// session($userId,null);
		// session($elemData['userId'],null);
		ajaxReturn(['status'=>1,'msg'=>'退出成功']);
	}

	public function getElemRefreshToken(){
		$userId = Request::instance()->param('userId');
		$elemData = session($userId);
		if(!empty($elemData)){
			$elemTokenData = session($elemData['userId']);
			$elemTokenArr = json_decode(json_encode($elemTokenData),true);
			$elemToken = $elemTokenArr['access_token'];
			return json(['status'=>1,'refresh_token'=>$elemToken]);
		}else{
			return json(['status'=>0,'shopInfo'=>[]]);
		}
	}

	/**
	 * [filterOrders 过滤饿了么订单取得没有配送的订单(饿了么订单status状态不明确)]
	 * @param  [type] $data [饿了么返回来的所有订单]
	 * @return [type]       [description]
	 */
	// public function filterOrders($data){
	// 	$arr = json_decode($data,true);
	// 	$list = $arr['list'];
	// 	if(!empty($list)){
	// 		$filterData['list'] = [];
	// 		foreach($list as $key => $val){
	// 			if($val['status'] == 'valid'){
	// 				$filterData['list'][] = $list[$key];
	// 			}
	// 		}
	// 	}
	// 	return json_encode($list);
	// }
    
}

// <pre>array(1) {
//   ["think"] =&gt; array(2) {
//     [374] =&gt; array(4) {
//       ["userId"] =&gt; int(393585216979213492)
//       ["userName"] =&gt; string(16) "sandbox_25981554"
//       ["authorizedShops"] =&gt; array(1) {
//         [0] =&gt; array(2) {
//           ["id"] =&gt; int(163785662)
//           ["name"] =&gt; string(24) "三只小鸡测试店铺"
//         }
//       }
//       ["expires_time"] =&gt; int(1529990285)
//     }
//     [393585216979213492] =&gt; object(stdClass)#16 (4) {
//       ["access_token"] =&gt; string(32) "15ccff20e106c5d0bd5759c8d526c631"
//       ["token_type"] =&gt; string(6) "Bearer"
//       ["expires_in"] =&gt; int(86400)
//       ["refresh_token"] =&gt; string(32) "721b2a5a56d1e208a752434f72620ada"
//     }
//   }
// }
// </pre><pre>array(1) {
//   ["think"] =&gt; array(2) {
//     [374] =&gt; array(4) {
//       ["userId"] =&gt; int(393585216979213492)
//       ["userName"] =&gt; string(16) "sandbox_25981554"
//       ["authorizedShops"] =&gt; array(1) {
//         [0] =&gt; array(2) {
//           ["id"] =&gt; int(163785662)
//           ["name"] =&gt; string(24) "三只小鸡测试店铺"
//         }
//       }
//       ["expires_time"] =&gt; int(1529990285)
//     }
//     [393585216979213492] =&gt; object(stdClass)#16 (4) {
//       ["access_token"] =&gt; string(32) "15ccff20e106c5d0bd5759c8d526c631"
//       ["token_type"] =&gt; string(6) "Bearer"
//       ["expires_in"] =&gt; int(86400)
//       ["refresh_token"] =&gt; string(32) "721b2a5a56d1e208a752434f72620ada"
//     }
//   }
// }
// </pre>{"status":1,"data":{"userId":393585216979213492,"userName":"sandbox_25981554","authorizedShops":[{"id":163785662,"name":"三只小鸡测试店铺"}],"expires_time":1529990285},"token":{"access_token":"15ccff20e106c5d0bd5759c8d526c631","token_type":"Bearer","expires_in":86400,"refresh_token":"721b2a5a56d1e208a752434f72620ada"}}